package com.ocr.demo;

import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;

import javax.swing.*;
import java.awt.*;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.io.File;
import java.util.List;

public class ImageUploader extends JFrame {
    private JLabel imageLabel;
    private File newimageFile;
    private JTextArea sbArea; //识别结果
    private JTextArea textArea;//文件路径
    private boolean isOk;//文件路径
    private int timeConsuming;//本次识别耗时

    public ImageUploader() {
        // 创建窗口和布局
        setTitle("证件识别");
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        setSize(800, 800);
        setLocationRelativeTo(null);
        setLayout(new BorderLayout());
        // 创建标签用于显示图片
        imageLabel = new JLabel();
        add(imageLabel);
        sbArea = new JTextArea(15, 30); // 创建一个10行、30列的文本框
        sbArea.setEditable(false); // 禁止输入
        JScrollPane scrollPane = new JScrollPane(sbArea); // 将文本框放入滚动窗格中

        // 创建按钮用于触发图片上传
      /*  JButton uploadButton = new JButton("上传图片");
        uploadButton.addActionListener(e -> {
            JFileChooser fileChooser = new JFileChooser();
            int result = fileChooser.showOpenDialog(this);

            if (result == JFileChooser.APPROVE_OPTION) {
                File selectedFile = fileChooser.getSelectedFile();
                displayImage(selectedFile);
            }
        });*/
        // 创建文本区域用于显示文件路径
        textArea = new JTextArea(6, 30);
        JScrollPane fileNamescrollPane = new JScrollPane(textArea);
        // 设置文本区域可接受拖拽操作
        textArea.setText("请将图片文件拖转至此处.后自动识别,可多次拖拽...");
        textArea.setTransferHandler(new ImageUploader.FileDropHandler());
      /*  JButton sbButton = new JButton("识别");
        //识别
        sbButton.addActionListener(e -> {
            ocrStart();
        });*/

        JPanel bottomPanel = new JPanel(new FlowLayout());

        //    bottomPanel.add(uploadButton);
        bottomPanel.add(fileNamescrollPane);
        //  bottomPanel.add(sbButton);
        bottomPanel.add(scrollPane);

        add(bottomPanel, BorderLayout.SOUTH);


        setVisible(true);
    }

    private void ocrStart() {
        if (this.newimageFile != null) {
            StringBuilder text = new StringBuilder();
            String message = OcrUtils.post(newimageFile, 0.5f);
            //  String message = OcrUtils.yasuo(newimageFile,1f);
          /*  System.out.println(message);
            JSONObject jsonObject = JSONUtil.parseObj(message);
            JSONArray results = jsonObject.getJSONArray("results");
            JSONObject datas = results.getJSONObject(0);
            JSONArray datalist = datas.getJSONArray("data");
            //包装新的json格式
            JSONObject jnewData = new JSONObject();
            for (int i = 0; i < datalist.size(); i++) {
                String lvalue = datalist.getJSONObject(i).getStr("text");
                //解析身份证信息
                String[] parm = OcrUtils.analysisIdCard(lvalue);
                jnewData.set(parm[0], parm[1]);
                text.append(lvalue).append("\n");
            }*/
            //sbArea.setText(text.toString());
            sbArea.setText(message);

            sbArea.append("\n本次识别耗时:" + timeConsuming + " ms");
            isOk = true;
            this.newimageFile = null;

        } else {
            JOptionPane.showMessageDialog(null, "图片为空,或图片已识别", "错误:", JOptionPane.ERROR_MESSAGE);
        }
    }

    private class FileDropHandler extends TransferHandler {
        @Override
        public boolean canImport(TransferSupport support) {
            // 只允许拖拽操作导入文件
            return support.isDataFlavorSupported(DataFlavor.javaFileListFlavor);
        }

        @Override
        public boolean importData(TransferSupport support) {
            if (!canImport(support)) {
                return false;
            }

            // 获取拖拽操作中的文件列表
            Transferable transferable = support.getTransferable();
            try {
                java.util.List<File> fileList = (List<File>) transferable.getTransferData(DataFlavor.javaFileListFlavor);

                // 处理每个文件
                for (File file : fileList) {
                    processFile(file);
                }

                return true;
            } catch (Exception e) {
                e.printStackTrace();
                return false;
            }
        }

        private void processFile(File file) {

            // 处理文件的逻辑，这里只简单地将文件路径显示在文本区域中
            System.out.println(file.getAbsolutePath() + "\n");
            // 获取文件后缀名
            String extension = getFileExtension(file);
            if (isImageExtension(extension)) {
                textArea.setText(file.getAbsolutePath() + "\n");
                isOk = false;
                //异步调用
                Thread lodingt = new Thread(() -> {
                    StringBuilder loding = new StringBuilder();
                    loding.append("正在识别请稍等");
                    timeConsuming = 0;
                    while (!isOk) {
                        try {
                            loding.append("...");
                            sbArea.setText(loding.toString());
                            Thread.sleep(200);
                            timeConsuming += 200;
                            if (timeConsuming >= 1000 * 30) {//设置超时30秒
                                isOk = true;
                                System.out.println("超时...");
                                sbArea.setText("程序错误已超时,请重试");
                            }
                        } catch (InterruptedException e) {
                            e.printStackTrace();
                        }
                    }
                });
                lodingt.start();
                newimageFile = file;
                displayImage(newimageFile);
                //异步调用
                Thread thread = new Thread(() -> {
                    // 调用异步方法
                    ocrStart();
                });
                thread.start();
            } else {
                textArea.setText("只支持jpg 和png格式图片");
                JOptionPane.showMessageDialog(null, "只支持jpg 和png格式图片", "错误:", JOptionPane.ERROR_MESSAGE);
            }
        }

        private String getFileExtension(File file) {
            String fileName = file.getName();
            int dotIndex = fileName.lastIndexOf(".");
            if (dotIndex > 0 && dotIndex < fileName.length() - 1) {
                return fileName.substring(dotIndex + 1).toLowerCase();
            }
            return "";
        }

        private boolean isImageExtension(String extension) {
            return extension.equals("jpg") || extension.equals("jpeg") || extension.equals("png");
        }
    }

    private void displayImage(File imageFile) {
        this.newimageFile = imageFile;
        // 将图片文件加载为Image对象
        ImageIcon imageIcon = new ImageIcon(imageFile.getAbsolutePath());
        Image image = imageIcon.getImage();

        // 按比例缩放图片
        Image scaledImage = image.getScaledInstance(imageLabel.getWidth(), imageLabel.getHeight(), Image.SCALE_SMOOTH);

        // 将缩放后的图片显示在标签上
        imageLabel.setIcon(new ImageIcon(scaledImage));
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(ImageUploader::new);
    }
}
